<?php
/**
 * Created by Yevgen Vershynin.
 * User: Yevgen Vershynin
 * Description: Model for Office entity.
 */

class OfficeModel {

    public function getOfficeById($officeId)
    {
        $db = DbComponent::getInstance();
        $rawData = $db->queryRow("SELECT * FROM offices WHERE officeCode = ".$officeId);

        if(!empty($rawData))
        {
            $office = new OfficeObject($rawData);
        }
        else
        {
            $office = array("error"=>"Wrong office code.");
        }

        return $office;
    }

    public function getAllOffices()
    {
        $db = DbComponent::getInstance();
        $rawData = $db->queryAll("SELECT * FROM offices");

        if(!empty($rawData))
        {
            foreach($rawData as $officeData)
            {
                $offices[] = new OfficeObject($officeData);
            }
        }
        else
        {
            $offices = array("error"=>"There is no offices");
        }

        return $offices;
    }

    public function createOffice($officeData)
    {
        $office = new OfficeObject($officeData);
        $db = DbComponent::getInstance();
        $affectedRows = $db->insert(
            "INSERT INTO offices(officeCode, city, phone, addressLine1, addressLine2, state, country,
            postalCode, territory)
            select (MAX(officeCode)+1), '$office->city','$office->phone','$office->street1'
            ,'$office->street2','$office->state','$office->country','$office->postalCode','$office->territory'
            FROM offices
        ");

        return ($affectedRows > 0);
    }

    public function updateOffice($officeData)
    {
        $office = new OfficeObject($officeData);
        if(!empty($office->code))
        {
            $db = DbComponent::getInstance();
            $affectedRows = $db->insert(
                "UPDATE offices set city='$office->city', phone='$office->phone', addressLine1='$office->street1',
                addressLine2='$office->street2', state='$office->state', country='$office->country',
                postalCode='$office->postalCode', territory='$office->territory'
                WHERE officeCode = $office->code
            ");

            return ($affectedRows > 0);
        }
        else
        {
            return false;
        }
    }

    public function deleteOffice($officeId)
    {
        $db = DbComponent::getInstance();
        $affectedRows = $db->insert("DELETE FROM offices WHERE officeCode=".$officeId);
        return ($affectedRows > 0);
    }
}